package org.reborn.engine.input.jinput

import org.reborn.engine.input._
import org.reborn.utils.PropertyUtil
import net.java.games.input.{Keyboard => JIKeyboard, Component}

/**
 * A JInput implementation of a Keyboard InputDevice
 */
class JInputKeyboard(val jiKeyboard:JIKeyboard) extends Keyboard {
  val deviceName = "JInput Keyboard - " + jiKeyboard.getName()
	
  protected var components:Map[KeyboardKey.KeyboardKey,JIButton] = Map()
  
  jiKeyboard.getComponents.toList.foreach{(comp) =>
	val jiIdent = comp.getIdentifier.getName
	val entry = JInputKeyboard.JIToComponentMap.get.get(jiIdent)
	entry.foreach{(name) =>
	  try{
		val key = Keyboard.Keys.withName(name)
		components += (key -> new JIButton(name, comp))
	  }
	  catch{
	 	  case _:NoSuchElementException => {System.err.println("Could not map JInput Identifier - "+jiIdent+" - to Key - "+name)}
	  }
	}
  }
  
  def poll():Unit = {
	jiKeyboard.poll
	for((name, component) <- components){
	  component.updateComponentState
	}
  }
  
  def keydown(key:KeyboardKey.KeyboardKey):Boolean = {
	getKeyComponent(key).foreach{(button) => 
	  return button.pressed
	}
	return false;
  }
  
  def getKeyComponent(key:KeyboardKey.KeyboardKey):Option[ButtonComponent] = {
	components.get(key)
  }
  
}

object JInputKeyboard{
  val JINPUT_KEYBOARD_PROPS = "org/reborn/engine/input/jinput/jinput-keyboard.properties"  
  lazy val JIToComponentMap = PropertyUtil.ReadProperties(JINPUT_KEYBOARD_PROPS)
}